import {Component, Input, OnInit} from '@angular/core';
import {LocalDataSource} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {ActivatedRoute} from "@angular/router";
import {NbDateService, NbDialogService} from "@nebular/theme";
import {CommonFormDialog} from "../../utils/CommonFormDialog";
import {CustomDateRender} from "../../utils/CustomDateRender";
import {DisableEditRender} from "../../utils/DisableEditRender";
import {UURBindDialogRender} from "./UURBindDialogRender";
import {AdminService} from "../../AdminService";
import {DocService} from "../../energy/api";
import {BaseRequest} from "../../utils/BaseRequest";
import {UserInfo} from "../../energy/api/model/userInfo";
import {map} from "rxjs/operators";
import {ResponseUserInfo} from "../../energy/api/model/responseUserInfo";

@Component({
  selector: 'user-document-component',
  templateUrl: './user-document.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    button {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 10px;
    }

    .margin {
      margin: 10px;
    }
  `],
})
export class UserDocumentComponent implements OnInit{
  @Input("unitId") unitIdI;
  @Input("showFilter") showFilter:boolean;
  settings = {
    pager:{
      display:true,
      perPage: 20
    },
    hideSubHeader: true,
    actions: {
      add: false,
      columnTitle: '操作',
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      userId: {
        title: 'ID',
        type: 'number',
      },
      userName: {
        title: '用户名称',
        type: 'string',
      },
      unitId: {
        title: '单元ID',
        type: 'custom',
        editable: false,
        editor:{
          type: 'custom',
          component: DisableEditRender
        },
        renderComponent: UURBindDialogRender,
        onComponentInitFunction:(instance)=>{
          instance.save.subscribe(result=>{
            if(result['oldUnitId']==result['unitId']) return;
            const query = [];
            if(result['uurId']!=null){
              query.push({
                operateType:"2",
                unitId: result['oldUnitId'],
                userId: result['userId']
              })
            }
            query.push({
              operateType:"0",
              unitId: result['unitId'],
              userId: result['userId']
            });
            this.api.postECASyncUserUnitRelInfo(new BaseRequest(query)).toPromise().then(response=>{
              if(response.success){
                this.source.refresh();
              }else{
                console.log(response);
              }
            })
          });
        }
      },
      corpName: {
        title: '公司名称',
        type: 'string',
      },
      teamName: {
        title: '团队名称',
        type: 'string',
      },
      address: {
        title: '地址',
        type: 'string',
      },
      telephone: {
        title: '联系电话',
        type: 'string',
      },
      identNo: {
        title: '身份证',
        type: 'string',
      },
      createDate: {
        title: '创建日期',
        type: 'custom',
        renderComponent: CustomDateRender,
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
    },
  };
  source: DataDataSource;
  maxPage:number = 1;
  page:number = 1;
  limit:number = 25;
  unitId?:number = null;
  userName:string = '';
  startTime:Date = null;
  endTime:Date = null;
  constructor(private service: SmartTableData
              ,private api:DocService
              ,private route:ActivatedRoute
              , private dialogService: NbDialogService
              ,private dateService:NbDateService<Date>
              ,private admin:AdminService) {

  }
  ngOnInit(): void {
    if(this.unitIdI==null) {
      this.route.paramMap.subscribe(value => {
        const unitId = value.get('unitId');
        if (unitId != null) this.unitId = Number(unitId);
        this.source = new DataDataSource(this.api, this.dateService, this.unitId);
      });
    }else{
      this.unitId = Number(this.unitIdI);
      this.source = new DataDataSource(this.api, this.dateService, this.unitId);
    }
  }

  filter(){
    this.source.userName = this.userName;
    this.source.startTime = this.startTime;
    this.source.endTime = this.endTime;
    this.source.setPage(1);
    this.source.refresh();
  }

  openAddPrompt(){
    const keys = Object.keys(this.settings.columns).filter(k => {
      return (this.settings.columns[k]['type'] == 'string' || this.settings.columns[k]['type'] == 'number')
        && this.settings.columns[k]['title'] != 'ID' && k!='unitId' && k!='createDate'
    });
    const columns = keys.map(k => {
      return {title:this.settings.columns[k].title,type:'input'};
    });
    this.dialogService.open(CommonFormDialog,{
      context:{
        data:columns,
        title: '新建用户'
      }
    }).onClose.subscribe(results=>{
      const data = <UserInfo>{};
      keys.forEach((k, i) => {
        if (columns[i]['type'] == 'number') {
          data[k] = Number(results[i]);
        } else {
          data[k] = results[i];
        }
      });
      data['operateType'] = "0";
      delete data['unitId'];
      this.api.postECASyncUserInfo(new BaseRequest([data])).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    })
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECASyncUserInfo(new BaseRequest(
        [{
          operateType:"2",
          userId:event.data['userId'],
        }]
    )).toPromise().then(res=>{
        if(res.success){
          event.confirm.resolve();
        }else{
          event.confirm.reject();
        }
      }).catch(e=>{
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event):void {
    const newData = event.newData;
    newData['operateType']="1";
    this.api.postECASyncUserInfo(new BaseRequest([newData])).toPromise().then(response=>{
      console.log(response);
      event.confirm.resolve();
    }).catch(e=>{
      console.log(e);
      event.confirm.reject();
    })
  }

}


export class DataDataSource extends LocalDataSource {
  userName:string = '';
  startTime:Date = null;
  endTime:Date = null;
  all: number = -1;
  constructor(private api: DocService,private dateService:NbDateService<Date>,private unitId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      unitId: this.unitId
    };
    if(this.userName!='') query['userName'] = this.userName;
    if(this.startTime!=null) query['startDate'] = this.dateService.format(this.startTime,'yyyyMMdd');
    if(this.endTime!=null) query['endDate'] = this.dateService.format(this.endTime,'yyyyMMdd');
    return this.api.requestECAUserInfo(new BaseRequest(query)).pipe(map((res:ResponseUserInfo)=>{
      this.all = res.dataCount;
      return res.data;
    })).toPromise();
  }
}


